import asyncio, pyautogui, random

from core.base_controller import BaseController
from core.utils import focus_wow

class MouseClickController(BaseController):

    async def mouse_click(self, mouse_key, interval):
        """ 定时任务 press_key """
        while True:
            await self.ws_client.broadcast_log(message_content=f"click_mouse_{mouse_key}", message_type=1)
            x, y = pyautogui.position()
            pyautogui.click(x=x, y=y, button=mouse_key, duration=0)
            try:
                await asyncio.sleep(random.uniform(interval - 0.2, interval + 0.2))  # 任务可以被取消
            except asyncio.CancelledError:
                await self.ws_client.broadcast_log(message_content=f"click_mouse_{mouse_key} 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def start(self, extra_data = {}):
        self.extra_data = extra_data
        """ 启动所有定时任务 """
        await self.stop_all_task()  # 停止之前所有任务
        
        task = asyncio.create_task(self.mouse_click(extra_data.get("mouse_key", "left"), extra_data.get("interval", 1)))  # 创建任务
        self.add_task(task)  # 添加任务到列表
            

    async def stop(self):
        """ 停止定时器 """
        await self.stop_all_task()  # 停止所有任务